package com.example.socialapp.ui.auth.register

import androidx.lifecycle.viewModelScope
import com.example.socialapp.domain.usecase.auth.RegisterUseCase
import com.example.socialapp.ui.base.mvi.MviViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import timber.log.Timber
import javax.inject.Inject

/**
 * 注册界面的ViewModel
 */
@HiltViewModel
class RegisterViewModel @Inject constructor(
    private val registerUseCase: RegisterUseCase
) : MviViewModel<RegisterState, RegisterIntent, RegisterEffect>() {

    override fun createInitialState(): RegisterState = RegisterState()

    override fun processIntent(intent: RegisterIntent) {
        when (intent) {
            is RegisterIntent.UpdateEmail -> updateEmail(intent.email)
            is RegisterIntent.UpdatePassword -> updatePassword(intent.password)
            is RegisterIntent.UpdateConfirmPassword -> updateConfirmPassword(intent.confirmPassword)
            is RegisterIntent.UpdateDisplayName -> updateDisplayName(intent.displayName)
            is RegisterIntent.UpdatePhoneNumber -> updatePhoneNumber(intent.phoneNumber)
            is RegisterIntent.ToggleTerms -> toggleTerms(intent.accepted)
            is RegisterIntent.SubmitRegister -> submitRegister()
            is RegisterIntent.NavigateToLogin -> navigateToLogin()
            is RegisterIntent.NavigateToTerms -> navigateToTerms()
            is RegisterIntent.RegisterWithGoogle -> registerWithGoogle()
            is RegisterIntent.RegisterWithFacebook -> registerWithFacebook()
            is RegisterIntent.RegisterWithApple -> registerWithApple()
        }
    }

    /**
     * 更新邮箱
     */
    private fun updateEmail(email: String) {
        updateState { it.copy(
            email = email,
            isEmailError = false,
            emailErrorMessage = ""
        ) }
    }

    /**
     * 更新密码
     */
    private fun updatePassword(password: String) {
        updateState { it.copy(
            password = password,
            isPasswordError = false,
            passwordErrorMessage = ""
        ) }
    }

    /**
     * 更新确认密码
     */
    private fun updateConfirmPassword(confirmPassword: String) {
        updateState { it.copy(
            confirmPassword = confirmPassword,
            isConfirmPasswordError = false,
            confirmPasswordErrorMessage = ""
        ) }
    }

    /**
     * 更新显示名称
     */
    private fun updateDisplayName(displayName: String) {
        updateState { it.copy(
            displayName = displayName,
            isDisplayNameError = false,
            displayNameErrorMessage = ""
        ) }
    }

    /**
     * 更新手机号
     */
    private fun updatePhoneNumber(phoneNumber: String) {
        updateState { it.copy(
            phoneNumber = phoneNumber,
            isPhoneNumberError = false,
            phoneNumberErrorMessage = ""
        ) }
    }

    /**
     * 切换条款接受状态
     */
    private fun toggleTerms(accepted: Boolean) {
        updateState { it.copy(
            acceptedTerms = accepted,
            isTermsError = false,
            termsErrorMessage = ""
        ) }
    }

    /**
     * 提交注册表单
     */
    private fun submitRegister() {
        val currentState = state.value
        
        // 检查是否接受条款
        if (!currentState.acceptedTerms) {
            updateState { it.copy(
                isTermsError = true,
                termsErrorMessage = "请先接受用户协议和隐私政策"
            ) }
            return
        }
        
        // 设置加载状态
        updateState { it.copy(isLoading = true) }
        
        viewModelScope.launch {
            registerUseCase(
                email = currentState.email,
                password = currentState.password,
                confirmPassword = currentState.confirmPassword,
                displayName = currentState.displayName,
                phoneNumber = currentState.phoneNumber.takeIf { it.isNotBlank() }
            ).onSuccess { user ->
                Timber.d("注册成功，用户邮箱: ${user.email}")
                updateState { it.copy(isLoading = false) }
                emitEffect(RegisterEffect.ShowSuccess("注册成功"))
                emitEffect(RegisterEffect.NavigateToMain)
            }.onFailure { error ->
                Timber.e(error, "注册失败")
                
                when {
                    error.message?.contains("邮箱") == true -> {
                        updateState { it.copy(
                            isLoading = false,
                            isEmailError = true,
                            emailErrorMessage = error.message ?: "邮箱无效"
                        ) }
                    }
                    error.message?.contains("密码") == true -> {
                        if (error.message?.contains("不一致") == true) {
                            updateState { it.copy(
                                isLoading = false,
                                isConfirmPasswordError = true,
                                confirmPasswordErrorMessage = error.message ?: "密码不一致"
                            ) }
                        } else {
                            updateState { it.copy(
                                isLoading = false,
                                isPasswordError = true,
                                passwordErrorMessage = error.message ?: "密码无效"
                            ) }
                        }
                    }
                    error.message?.contains("用户名") == true -> {
                        updateState { it.copy(
                            isLoading = false,
                            isDisplayNameError = true,
                            displayNameErrorMessage = error.message ?: "用户名无效"
                        ) }
                    }
                    error.message?.contains("手机号") == true -> {
                        updateState { it.copy(
                            isLoading = false,
                            isPhoneNumberError = true,
                            phoneNumberErrorMessage = error.message ?: "手机号无效"
                        ) }
                    }
                    else -> {
                        updateState { it.copy(isLoading = false) }
                        emitEffect(RegisterEffect.ShowError(error.message ?: "注册失败"))
                    }
                }
            }
        }
    }

    /**
     * 导航到登录界面
     */
    private fun navigateToLogin() {
        emitEffect(RegisterEffect.NavigateToLogin)
    }

    /**
     * 导航到条款界面
     */
    private fun navigateToTerms() {
        emitEffect(RegisterEffect.NavigateToTerms)
    }

    /**
     * 使用Google注册
     */
    private fun registerWithGoogle() {
        emitEffect(RegisterEffect.LaunchGoogleSignIn)
    }

    /**
     * 使用Facebook注册
     */
    private fun registerWithFacebook() {
        emitEffect(RegisterEffect.LaunchFacebookSignIn)
    }

    /**
     * 使用Apple注册
     */
    private fun registerWithApple() {
        emitEffect(RegisterEffect.LaunchAppleSignIn)
    }
} 